package com.itheima.reggie.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.EmployeeStr;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService service;
    //分页查询员工数据
    @GetMapping("/page")
    public R pageQuery(Integer page, Integer pageSize, String name) {
        //进行带条件分页查询
        IPage<Employee> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        //封装查询条件
        if (StringUtils.isNotEmpty(name)) {
            qw.like(Employee::getName, name);
        }
        qw.orderByDesc(Employee::getUpdateTime);
        service.page(pageInfo, qw);
        //通过pageInfo获取分页结果 list<>集合  总记录数
        List<Employee> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        Map data = new HashMap<>();
        data.put("records", records);
        data.put("total", total);
        return R.success(data);
    }

    //用于完成用户登录的方法
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session) {
        if (employee == null || StringUtils.isEmpty(employee.getUsername())
                || StringUtils.isEmpty(employee.getPassword())) {
            return R.error("用户名或密码不能为空");
        }
        //查询数据库 select * from employee where username = ?
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee employOne = service.getOne(qw);
        if (employOne == null) {
            return R.error("此用户不存在");
        }
        if (employOne.getStatus() == 0) {
            return R.error("此用户已禁用");
        }
        //数据库的Employee（密文） 和 用户输入的（明文）比较
        String password1 = employOne.getPassword();// 密码为密文
        String password2 = employee.getPassword(); //密码为明文
        password2 = DigestUtils.md5DigestAsHex(password2.getBytes());
        if (!password2.equals(password1)) {
            return R.error("密码错误");
        }
        //比对成功，返回code:1 和 data:用户信息 ，将用户数据存入会话中（session）
        session.setAttribute("employee", employOne);
        employOne.setPassword(null);
        return R.success(employOne);
    }

    //用户登出
    @PostMapping("/logout")
    public R loginOut(HttpSession session) {
        //清除session中登录的用户数据
        session.removeAttribute("employee");
        return R.success(null);
    }

    //添加员工
    @PostMapping
    public R saveEmployee(@RequestBody Employee employee, HttpSession session) {

        //检查数据，哪些是需要处理的
        //密码使用默认的123456，需要加密处理 DigestUtils.md5DigestAsHex
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());


        //status不需要处理，数据库默认是1
        //  employee.setCreateTime(LocalDateTime.now());
        //  employee.setUpdateTime(LocalDateTime.now());
        //CreateUser，UpdateUser 应该是当前登录人
      /*  Employee employee1 = (Employee) session.getAttribute("employee");
        employee.setCreateUser(employee1.getId());
        employee.setUpdateUser(employee1.getId());*/
        //调用业务层保存 employee数据
        boolean save = service.save(employee);

        //返回结果R
        if (save) {
            return R.success(null);
        } else {
            return R.error("保存失败");
        }
    }

    //更改员工状态
    @PutMapping
    public R updateEmployee(@RequestBody Employee employee, HttpSession session) {
       /* Employee employee1 = (Employee) session.getAttribute("employee");
        Long id = employee1.getId();
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(id);*/
        service.updateById(employee);
        return R.success("员工修改成功");
    }

    //按id查询员工
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        Employee employee = service.getById(id);
        if (employee != null) {
            return R.success(employee);
        }
        return R.error("没有查询到对应员工的信息");
    }
    //导出员工数据
    @GetMapping("/export")
    public void exportEmployee(HttpServletResponse response) {
        try {
            response.setHeader("Content-Disposition",
                    "attachment; filename=employee.xlsx");
            List<Employee> list = service.list();
           List<EmployeeStr> employeeStrList = new ArrayList<>();
            for (Employee employee : list) {
                EmployeeStr employeeStr = new EmployeeStr();
                BeanUtils.copyProperties(employee,employeeStr);

                String s = employee.getId().toString();
                employeeStr.setIdStr(s);
                String sex = employee.getSex();
                if ("0".equals(sex)) {
                    employeeStr.setSex("女");
                } else {
                    employeeStr.setSex("男");
                }
                Integer status = employee.getStatus();
                if (status == 1) {
                    employeeStr.setStatusStr("在职");
                }else {
                    employeeStr.setStatusStr("离职");
                }
                Employee byId = service.getById(employee.getCreateUser());
                employeeStr.setCreateUserStr(byId.getName());
                employeeStr.setUpdateUserStr(byId.getName());
                employeeStrList.add(employeeStr);
            }
            ServletOutputStream outputStream = response.getOutputStream();
            EasyExcel.write(outputStream,EmployeeStr.class).sheet("员工数据").doWrite(employeeStrList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
